﻿using System;
using System.Configuration;
using System.IO;
using System.Web;

namespace PmfWeb.Core.Errors
{
    ///<summary>
    /// 站内错误日志记录者
    ///</summary>
    public class ErrorLogger
    {
        /// <summary>
        /// 添加错误信息
        /// </summary>
        /// <param name="ex"></param>
        public static void Add(Exception ex)
        {
            ErrorLoggerSection section = ConfigurationManager.GetSection("WebSiteErrorLogger") as ErrorLoggerSection;
            if (section != null)
            {
                string myDirectory = HttpContext.Current.Server.MapPath(section.Path + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/");
                string mypath = myDirectory + DateTime.Now.ToShortDateString() + ".txt";
                if (!Directory.Exists(myDirectory))
                {
                    Directory.CreateDirectory(myDirectory);
                }
                File.AppendAllText(mypath, string.Format("{0:yyyyMMdd_HHmmss} :: {1}{2}{2}", DateTime.Now, ex, Environment.NewLine));
            }
            else
            {
                throw new System.Exception("在站点web.config文件中未发现'ErrorLoggerSection'配置字节!");
            } 
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="filePath">日志文件路径</param>
        /// <param name="message">信息</param>
        /// <returns>是否记录成功</returns>
        public static bool Add(string filePath, string message)
        {
            ErrorLoggerSection section = ConfigurationManager.GetSection("WebSiteErrorLogger") as ErrorLoggerSection;
            if (null == section) throw new Exception("在站点web.config文件中未发现'ErrorLoggerSection'配置字节!");
            object obj = new object();
            lock (obj)
            {
                try
                {
                    File.AppendAllText(filePath, message);
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
    }

    ///<summary>
    /// web.config文件中配置的节
    ///</summary>
    public class ErrorLoggerSection : ConfigurationSection
    {
        ///<summary>
        /// 错误文件存放位置
        ///</summary>
        [ConfigurationProperty("Path",IsRequired = true)]
        public string Path
        {
            get
            {
                return base["Path"].ToString();
            }
            set
            {
                base["Path"] = value;
            }
        }

    }
}
